//
//  UIViewController+BaseBaseBusiness.m
//  LBBase
//
//  Created by Gary on 15/9/13

//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "UIViewController+BaseBusiness.h"
#import "UINavigationBar+Awesome.h"

#import "BusinessFramework.h"
#import "BusinessListener.h"
#import "BaseBusinessProtocol.h"

#import "ModuleDefine.h"
#import "Common.h"
#import "WebPageViewController.h"
#import "UIBarButtonItem+Badge.h"

@implementation UIViewController (BaseBusiness)

- (void)performViewDidLoad {
    
}

#pragma mark - Navigation Bar

- (void)initNavigationBar {
    if (self.navigationController) {
        self.navigationController.navigationBarHidden = NO;
        self.navigationController.navigationBar.backItem.backBarButtonItem = nil;
        [self.navigationController.navigationBar lt_setBackgroundColor:kNavigartionBarBgColor];
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                         [UIColor whiteColor], NSForegroundColorAttributeName,
                                                                         kNavigartionTitleFont, NSFontAttributeName,
                                                                         nil]];
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    }
}

- (void)defaultNavigationLeftBar {
    [self initNavigationBar];
    
    //初始化左边按钮
    NSMutableDictionary *leftDic = [Common getNavigationBarBtnFullSetting]; //获取带全属性的按钮字典
    [leftDic setObject:kNavigationBarBtnStyleImage forKey:kNavigationBarBtnStyleKey];    //设置按钮的风格为纯图片
    UIImage *image = [UIImage imageNamed:@"page_back"];
    CGFloat width = kNavigationBarIconHeight * image.size.width / image.size.height;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:MakeRect(0, 0, width, kNavigationBarIconHeight)];
    imageView.image = image;
    [leftDic setObject:@{kNavigationBarBtnBackgroundImagesNormalKey : imageView} forKey:kNavigationBarBtnBackgroundImagesKey]; //设置图片
    [leftDic setObject:self forKey:kNavigationBarBtnTargetKey];     //设置按钮响应的target
    [leftDic setObject:[NSValue valueWithBytes:&(@selector(pageBack)) objCType:@encode(SEL)]
                forKey:kNavigationBarBtnActionKey]; //设置按钮响应的action
    [self setNavigationLeftBar:leftDic];
}

- (void)setNavigationLeftBar:(NSMutableDictionary *)leftDic {
    //if (leftDic) {
        [leftDic setObject:self forKey:kNavigationBarBtnTargetKey];     //设置按钮响应的target
        if (![leftDic objectForKey:kNavigationBarBtnActionKey]) {
            [leftDic setObject:[NSValue valueWithBytes:&(@selector(pageBack)) objCType:@encode(SEL)]
                        forKey:kNavigationBarBtnActionKey];   //设置按钮响应的action
        }
        UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] init];
        UIBarButtonItem *leftOutBtn = nil;
        [Common setNavigationBarBtn:leftDic inButton:leftBtn outButton:&leftOutBtn];
        if (leftOutBtn) {
            leftBtn = leftOutBtn;
        }
        leftBtn.tintColor = [UIColor whiteColor];
        self.navigationItem.leftBarButtonItem = leftBtn;
    //}
}

- (void)setNavigationRightBar:(NSMutableDictionary*)rightDic {
    [rightDic setObject:self forKey:kNavigationBarBtnTargetKey];     //设置按钮响应的target
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] init];
    UIBarButtonItem *rightOutBtn = nil;
    [Common setNavigationBarBtn:rightDic inButton:rightBtn outButton:&rightOutBtn];
    if (rightOutBtn) {
        rightBtn = rightOutBtn;
    }
    rightBtn.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightBtn;
}

- (void)setNavigationBar:(NSString*)title left:(id)left right:(id)right {
    self.title = title;
    if (left) {
        UIBarButtonItem *buttonItem = nil;
        [Common setNavigationBarBtn:left inButton:self.navigationItem.backBarButtonItem outButton:&buttonItem];
        if (buttonItem) {
            self.navigationItem.backBarButtonItem = buttonItem;
        }
    }
    
    if (right) {
        UIBarButtonItem *buttonItem = nil;
        [Common setNavigationBarBtn:left inButton:self.navigationItem.rightBarButtonItem outButton:&buttonItem];
        if (buttonItem) {
            self.navigationItem.rightBarButtonItem = buttonItem;
        }
    }
}

- (void)addNavigationBarButtonItemBadge:(UIBarButtonItem *)barButtonItem {
    barButtonItem.badge.hidden = NO;
    barButtonItem.badgeValue = @" ";
    barButtonItem.badgeFont = MakeFont(1.f);
    barButtonItem.badgeOriginX = 22.f;
    barButtonItem.badgeOriginY = 12.f;
    barButtonItem.badgePadding = 5.f;
    barButtonItem.badgeMinSize = 2.f;
    barButtonItem.shouldAnimateBadge = YES;
}

#pragma mark - Page Style

- (BOOL)isPresent {
    if (self.navigationController) {
        return self == self.navigationController.viewControllers.lastObject;
    }
    return YES;
}

- (void)pageBack {
    if (self.navigationController) {
        [self popViewControllerAnimated:YES];
    }
}

- (void)popToViewController:(UIViewController*)viewController animated:(BOOL)animated {
    LogDebugFunc;
    if (self.navigationController) {
        NSArray *popped = [self.navigationController popToViewController:viewController animated:animated];
        if (popped) {
            for (UIViewController *vc in popped) {
                //LogDebug(@"vc: %@", NSStringFromClass(vc.class));
                if ([vc conformsToProtocol:@protocol(BaseBusinessProtocol)]) {
                    [(id<BaseBusinessProtocol>)vc unregisterBusinessListener];
                }
            }
        }
    }
}

- (UIViewController*)popToViewControllerKindClass:(id)viewControllerClass
                                         animated:(BOOL)animated {
    if (!viewControllerClass) {
        return nil;
    }
    
    NSArray *arr;
    if (![viewControllerClass isKindOfClass:[NSArray class]]) {
        arr = [NSArray arrayWithObject:viewControllerClass];
    } else {
        arr = viewControllerClass;
    }
    
    for (UIViewController *viewController in [self.navigationController.viewControllers reverseObjectEnumerator]) {
        for (Class class in arr) {
            if ([viewController isKindOfClass:class]) {
                [self popToViewController:viewController animated:animated];
                return viewController;
            }
        }
    }
    return nil;
}

- (UIViewController*)popToViewControllerMemberClass:(id)viewControllerClass
                                           animated:(BOOL)animated {
    if (!viewControllerClass) {
        return nil;
    }
    
    NSArray *arr;
    if (![viewControllerClass isKindOfClass:[NSArray class]]) {
        arr = [NSArray arrayWithObject:viewControllerClass];
    } else {
        arr = viewControllerClass;
    }
    
    for (UIViewController *viewController in [self.navigationController.viewControllers reverseObjectEnumerator]) {
        for (Class class in arr) {
            if ([viewController isMemberOfClass:class]) {
                [self popToViewController:viewController animated:animated];
                return viewController;
            }
        }
    }
    
    return nil;
}

- (void)popViewControllerAnimated:(BOOL)animated {
    if (self.navigationController) {
        if ([self.navigationController popViewControllerAnimated:animated]) {
            if ([self conformsToProtocol:@protocol(BaseBusinessProtocol)]) {
                [(id<BaseBusinessProtocol>)self unregisterBusinessListener];
            }
        }
    }
}

#pragma mark - Bussiniss Listener

- (void)registerBusinessListener {
    if ([self conformsToProtocol:@protocol(BusinessListenerProtocol)]) {
        if (![BF findBusinessListener:(id<BusinessListenerProtocol>)self]) {
            [BF registerBusinessListener:(id<BusinessListenerProtocol>)self];
        }
    }
}

- (void)unregisterBusinessListener {
    //LogDebugFunc;
    if ([self conformsToProtocol:@protocol(BusinessListenerProtocol)]) {
        if ([BF findBusinessListener:(id<BusinessListenerProtocol>)self]) {
            [BF unregisterBusinessListener:(id<BusinessListenerProtocol>)self];
        }
    }
}

- (void)onBusinessNotify:(NSUInteger)notifyID inParam:(id)inParam {
    
}

#pragma mark - Network Request & Response

- (NSMutableDictionary*)requestDic:(NSDictionary*)paramDic {
    NSMutableDictionary *dic;
    if (paramDic) {
        dic = [NSMutableDictionary dictionaryWithDictionary:paramDic];
    } else {
        dic = [NSMutableDictionary dictionary];
    }
    return dic;
}

- (NSDictionary*)makeRequestParams:(NSMutableDictionary*)requestDic
                       requestInfo:(NSDictionary*)requestInfo {
    NSMutableDictionary *infoDic;
    if (requestInfo) {
        infoDic = [NSMutableDictionary dictionaryWithDictionary:requestInfo];
    } else {
        infoDic = [NSMutableDictionary dictionary];
    }
    infoDic[kNetworkRequestSender] = [NSValue valueWithPointer:(__bridge const void *)(self)];
    if (requestDic) {
        return [NSDictionary dictionaryWithObjectsAndKeys:requestDic, kNetworkRequestData, infoDic, kNetworkRequestInfo, nil];
    } else {
        return [NSDictionary dictionaryWithObject:infoDic forKey:kNetworkRequestInfo];
    }
}

- (BOOL)isSender:(NSDictionary*)requestInfo {
    if (requestInfo) {
        NSValue *sender = requestInfo[kNetworkRequestSender];
        if (sender.pointerValue == (__bridge void *)(self)) {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)networkRequestFailed:(NSError*)error {
    return NO;
}

#pragma mark - Common Features

- (UIButton *)submitButton:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = kSubmitButtonFrame;
    button.layer.cornerRadius = kSubmitButtonCornerRadius;
    button.clipsToBounds = YES;
    [button setTitleColor:kSubmitButtonTextColor forState:UIControlStateNormal];
    [button setTitleColor:kSubmitButtonTextColorHighlighted forState:UIControlStateHighlighted];
    button.backgroundColor = kSubmitButtonBGColor;
    [button setTitle:title forState:UIControlStateNormal];
    return button;
}

- (void)changeSubmitButton:(UIButton*)button enabled:(BOOL)enabled {
    if (enabled == button.enabled) {
        return;
    }
    
    if (enabled) {
        button.enabled = YES;
        button.backgroundColor = kSubmitButtonBGColor;
        [button setTitleColor:kSubmitButtonTextColor forState:UIControlStateNormal];
    } else {
        button.enabled = NO;
        button.backgroundColor = kSubmitButtonBGColorUnable;
        //[button setTitleColor:kSubmitButtonTextColorUnable forState:UIControlStateNormal];
    }
}

- (void)showWebPage:(NSString *)title url:(NSURL *)url {
    WebPageViewController *vc = (WebPageViewController *)[Common viewController:@"WebPageViewController"
                                                                    storyboard:@"Utility"];
    vc.title = title;
    vc.webPageUrl = url;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
